package cn.touna.jss.modules.third.tencent;

import cn.touna.risk.api.contraints.facet.First;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.entity.CreditQueryRequest;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.mq.KafkaUtils;
import cn.touna.jss.common.properties.config.HbaseTableTopicProperties;
import cn.touna.jss.common.properties.disconf.TencentProperties;
import cn.touna.jss.common.util.*;
import cn.touna.jss.common.util.Base64;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.tencent.constant.TencentConstant;
import cn.touna.jss.modules.third.tencent.dto.FaceRecognizeRequest;
import cn.touna.jss.modules.third.tencent.dto.FaceResultReq;
import cn.touna.jss.modules.third.tencent.dto.IdcardRequest;
import cn.touna.jss.modules.third.tencent.dto.OcrRequest;
import cn.touna.jss.modules.third.tencent.entity.ApiVertifyFaceEntity;
import cn.touna.jss.modules.third.tencent.entity.TecentRequestEntity;
import cn.touna.jss.modules.third.tencent.util.FaceRecognizeUtil;
import cn.touna.jss.modules.third.tencent.util.TencentHttpUtil;
import cn.touna.jss.modules.third.tencent.util.TencentOcrUtil;
import cn.touna.jss.modules.third.tencent.util.TencentResponse;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.utils.ServiceContext;
import cn.touna.risk.cache.redis.RedisCache;
import cn.touna.risk.mq.common.Producer;
import cn.touna.risk.threadpool.common.util.ThreadPoolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.touna.loan.log.service.TracerContextUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

import static com.alibaba.fastjson.JSON.parseObject;

/**
 * 腾讯调用
 * Created by wuwuc on 2017/7/25.
 */
@Service
public class TencentService {

    private static final Logger logger = LogManager.getLogger(TencentService.class);
    private static final String FACE_CLICK_NAME="evnt_ckapp_face_reco";
    @Autowired
    private TencentProperties tencentProperties;

    @Resource(name = "httpsRestTemplate")
    private RestTemplate restTemplate;

    @Autowired
    private Producer producer;

    @Resource
    private RedisCache redisCache;

    @Autowired
    private HbaseTableTopicProperties topicProperties;

    @Autowired
    private OssClientUtil ossClientUtil;
    @Autowired
    FaceRecognizeUtil faceRecognizeUtil;

    /**
     * 腾讯反欺诈
     *
     * @param requestEntity
     * @return
     */
    @ApiMapping(value = "tencent.tencentAntiFraud",desc = "腾讯.反欺诈接口")
    public Response tencentAntiFraud(TecentRequestEntity requestEntity) {
        logger.info("REQ 【腾讯反欺诈】tencentAntiFraud-requestEntity：{}", requestEntity);
        Response<String> response = new Response<>();
        ValidUtil.checkRequestParams(requestEntity, First.class);
        SortedMap<String, String> arguments = new TreeMap<>();
        try {
            Map<String, String> reqparam = new HashMap<>();
            reqparam.put("idNumber", requestEntity.getIdCard());
            reqparam.put("phoneNumber", JssConstant.PHONE_CODE + requestEntity.getMobile());
            arguments.putAll(reqparam);
            arguments.put("Nonce", String.valueOf((int) (Math.random() * 0x7fffffff)));
            arguments.put("Action", JssConstant.ACTION_TENCENT);
            arguments.put("Region", tencentProperties.getRegion());
            arguments.put("SecretId", tencentProperties.getSecretId());
            arguments.put("Timestamp", String.valueOf(System.currentTimeMillis() / 1000));
            arguments.put("Signature", Common.hmacSHA1(tencentProperties.getSecretKey(), String.format("%s%s?%s", JssConstant.GET_METHOD, tencentProperties.getAntiFraudUrl(), Common.makeQueryString(arguments, null))));
            String requestUrl = String.format("https://%s?%s", tencentProperties.getAntiFraudUrl(), Common.makeQueryString(arguments, "utf-8"));
            TencentResponse res = TencentHttpUtil.sendGet(requestUrl, "");
            logger.info("RSP 调用【腾讯反欺诈-tecentAntiFraud】 返回结果：res:{}", res.getBody().toString());
            if (res != null && res.getBody() != null) {
                JSONObject respJson = parseObject(res.getBody().toString());
                if (respJson != null) {
                    int code = respJson.getInteger("code");
                    if (code == 0) {
//                        Map<String, Object> param = new HashMap<>();
//                        param.put("riskScore", respJson.getInteger("riskScore"));
//                        if (0 != respJson.getInteger("riskScore")) {
//                            param.put("riskInfo", respJson.get("riskInfo"));
//                        }
                        return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, res.getBody().toString());
                    }
                    String msg = respJson.getString("message");
                    return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, msg);
                }
            }
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR);
        } catch (Exception e) {
            logger.error("jss调用【腾讯反欺诈】异常,tencentAntiFraud,paramMap:{}", arguments, e);
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        }
    }
    /**
     ********************************************************************
     * 腾讯行驶证驾驶证识别
     * @param request Ocr车辆识别请求对象
     * @Author  zhangjialian
     * @return  cn.touna.risk.api.domain.Response
     * @date    2018/9/12 14:00
     ********************************************************************/
    @ApiMapping(value = "tencent.ocr.recognize", desc = "腾讯.OCR行驶证驾驶证识别", isFile = true)
    public Response ocrRecognize(OcrRequest request) throws Exception {
        logger.info("OCR 【腾讯行驶证驾驶证识别】TencentService-ocrRecognize begin");
        Response response =checkOcrRequest(request);
        if(response!=null){return response;}
        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
        //识别类型，0 表示行驶证，1 表示驾驶证，2 表示行驶证副页。
        requestBody.add("type", request.getType());
        requestBody.add("appid", tencentProperties.getOcrAppid().toString());
        requestBody.add("image", request.getImage());
        HttpEntity requestEntity = new HttpEntity(requestBody,getOcrHeader(request));
        ResponseEntity<String> responseEntity =null;
        try{
            responseEntity = restTemplate.exchange(tencentProperties.getOcrRecognityUrl(),
                    HttpMethod.POST, requestEntity, String.class);
        }catch(Exception e){
            logger.error("腾讯行驶证驾驶证识别调用异常:"+e);
            return new Response().fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(),TencentConstant.OCR_UNKNOW_ERROR_FROM_IMAGE);
        }
        String result =responseEntity.getBody();
        uploadFileToOss(TencentConstant.OCR_DRIVER_LICENSE_RECOGNIZE, MD5Util.MD5(new String(request.getImage())),
                "img",request.getImage());
        logger.info("OCR 【腾讯行驶证驾驶证识别】end：{}", result);
        return parseOcrResult(result);
    }

    /**
     ********************************************************************
     * 腾讯身份证识别
     * @param request 身份识别请求对象
     * @param file 身份证图片流
     * @Author  zhangjialian
     * @return  cn.touna.risk.api.domain.Response
     * @date    2018/9/12 14:00
     ********************************************************************/
    @ApiMapping(value = "tencent.idcardRecognize", desc = "腾讯.OCR身份证识别", isFile = true)
    public Response idcardRecognize(IdcardRequest request,byte[] file) throws Exception {
        Long currentTimeMills =System.currentTimeMillis();
        logger.info("IDCARD 【腾讯身份证识别请求类】TencentService-idcardRecognize begin"+request.toString());
        Response response =checkIdcardRequest(request,file);
        if(response!=null){return response;}
//        if (file != null && file.length < 4 * 1024 * 1024) {
//            response=new Response().fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(),TencentConstant.OCR_TOO_BIG_IMAGE);
//        }
        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("card_type", request.getType());
        requestBody.add("appid", tencentProperties.getOcrAppid().toString());
        if (null!=file){
            requestBody.add("image", file);
        } else if (file==null && StringUtils.isNotEmpty(request.getUrl())){
            requestBody.add("url_list", new String[]{request.getUrl()});
        }

        HttpEntity requestEntity = new HttpEntity(requestBody,getOcrHeader(file,request.getUrl()));
        ResponseEntity<String> responseEntity =null;
        try{
            responseEntity = restTemplate.exchange(tencentProperties.getIdcardRecognizeUrl(),
                    HttpMethod.POST, requestEntity, String.class);
        }catch(Exception e){
            logger.error("腾讯身份证识别调用异常:request={},errorMsg={}",request.toString(),e);
            response=new Response().fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(),TencentConstant.OCR_UNKNOW_ERROR_FROM_IMAGE);
        }
        String resultData =null;
        if(responseEntity!=null && StringUtils.isNotEmpty(responseEntity.getBody())){
            //上传单张相片,所以从result_list取第一张
            JSONObject result=JSON.parseObject(responseEntity.getBody());
            resultData=result.getJSONArray("result_list").getString(0);
            response=parseOcrResult(resultData);
        }else{
            if(response==null){
                response=new Response().fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(),TencentConstant.OCR_RESULT_NULL);
            }
        }
        logger.info("OCR 【腾讯身份证识别】,params={},costTime：{}ms",request.toString(),(System.currentTimeMillis()-currentTimeMills));
        //异步执行任务
        ThreadPoolUtil.submit("tencentPool", TracerContextUtil.getTraceId(),
        this, "saveAndSendMsg", request);
        uploadFileToOss(TencentConstant.IDCARD_RECOGNIZE,request.getImageMd5(),"img",file);
        return response;
    }
    /**
     ********************************************************************
     * 腾讯人脸识别认证
     * @param req 人脸识别请求对象
     * @Author  zhangjialian
     * @return  cn.touna.risk.api.domain.Response
     * @date    2018/9/12 14:01
     ********************************************************************/
    @ApiMapping(value = "tencent.faceRecognize", desc = "腾讯.人脸识别认证", isFile = true)
    public Response faceRecognize(FaceRecognizeRequest req){
        logger.info("IDCARD 【腾讯人脸识别】TencentService-faceRecognize begin:"+req.toString());
        Response res=FaceRecognizeUtil.checkParams(req);
        if(null!=res){return res;}
        Response response=new Response();
        String accessToken = faceRecognizeUtil.getAccessToken(response);//访问获取token
        if(StringUtils.isEmpty(accessToken)){return response;}
        String signTicket = faceRecognizeUtil.getTicket(accessToken,TencentConstant.FACE_TICKET_SIGN,null,response);//sign ticket
        if(StringUtils.isEmpty(signTicket)){return response;}
        List<String> signTicketData= FaceRecognizeUtil.getSignTicketData(tencentProperties.getFaceAppId(), req.getOrderNo(),req.getName(),req.getIdCard(),req.getUserId());
        String h5FaceIdSign = FaceRecognizeUtil.sign(signTicketData, signTicket);
        String h5faceid=faceRecognizeUtil.queryH5faceid(req,h5FaceIdSign,response);
        if(StringUtils.isEmpty(h5faceid)){return response;}
        String nonceTicket = faceRecognizeUtil.getTicket(accessToken,TencentConstant.FACE_TICKET_NONCE,req.getUserId(),response);//NONCE ticket
        if(StringUtils.isEmpty(nonceTicket)){return response;}
        String nonce= ServiceContext.genUniqueId();
        List<String> nonceTicketData= FaceRecognizeUtil.getNonceTicketData(tencentProperties.getFaceAppId(), req.getOrderNo(),req.getUserId(),h5faceid,nonce);
        String nonceSign = FaceRecognizeUtil.sign(nonceTicketData, nonceTicket);
        String faceVertifyUrl=faceRecognizeUtil.generateFaceVertifyUrl(req,h5faceid,nonce,nonceSign);
        return faceRecognizeUtil.generateFaceResult(req,response,h5faceid,faceVertifyUrl,signTicket,nonce);
    }
    /**
     ********************************************************************
     * 人脸识别异步查询人脸识别结果
     * @param req 人脸识别异步结果查询请求
     * @Author  zhangjialian
     * @return  cn.touna.risk.api.domain.Response
     * @date    2018/9/12 14:02
     ********************************************************************/
    @ApiMapping(value = "tencent.queryFaceResult",desc ="腾讯.异步查询人脸识别结果" )
    public Response queryFaceResult(FaceResultReq req){
        Response res=FaceRecognizeUtil.checkParams(req);
        if(null!=res){return res;}
        List<String> signTicketData= FaceRecognizeUtil.getfaceResultTicketData(tencentProperties.getFaceAppId(), req.getOrderNo(),req.getNonce());
        String sign = FaceRecognizeUtil.sign(signTicketData, req.getSignTicket());
        res=faceRecognizeUtil.queryFaceResult(req,sign);
        //异步执行推送人脸识别结果任务
        ThreadPoolUtil.submit("tencentPool", TracerContextUtil.getTraceId(),
                this, "sendFaceResultMsg", req,res,"tencent.queryFaceResult");
        return res;
    }


    /**
     * 保存请求信息至redis,并通过kafka推送变量系统,做后续统计
     * @param request 请求对象
     */
    private void saveAndSendMsg(IdcardRequest request) {
        String idcardKey=String.format(TencentConstant.REDIS_OCR_IDCARD_RECORD,request.getMobile(),request.getType());
        if(null==redisCache.hGet(idcardKey,request.getImageMd5())){
            redisCache.hPut(idcardKey,request.getImageMd5(),JSON.toJSONString(request));
            JSONObject jsonResult=new JSONObject();
            jsonResult.put("mobile",request.getMobile());
            jsonResult.put("type",request.getType());
            jsonResult.put("idcardCount",redisCache.hSize(idcardKey));
            sendAsyncMessage(jsonResult,JSON.parseObject(JSON.toJSONString(request)),"tencent.idcardRecognize");
        }
        logger.info("【腾讯身份证识别】当前用户：{},类型:{},身份证相片上传统计次数:{}", request.getMobile(),
                "0".equals(request.getType())?"正面":"反面",redisCache.hSize(idcardKey));
    }

    private void sendFaceResultMsg(FaceResultReq req,Response res,String methodName) {
        if(res.getData()==null ||
                !SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC.getErrorCode().equals(res.getCode())){
            logger.warn("人脸识别异步查询结果为空或调用失败,无需推送变量系统，res:{}",JSONObject.toJSONString(res));
            return ;
        }
        JSONObject data=JSON.parseObject(JSONObject.toJSONString(res.getData()));
        JSONObject result=data.getJSONObject("result");
        if(result!=null){
            JSONObject msg=new JSONObject();
            String idNo=result.getString("idNo");
            msg.put("phone_no",idNo); //变量系统埋点数据只有手机号标识，无身份证ID标识
            msg.put("id_card",idNo);
            msg.put("face_reco_is_succ","0".equals(data.getString("code"))?"true":"false");
            msg.put("face_rego_simi",result.getString("similarity"));
            msg.put("face_reco_sdt",result.getString("occurredTime"));
            msg.put("face_reco_edt",result.getString("transactionTime"));
            JSONObject kafkaData=ClickUtil.genClickData(idNo,idNo,msg,FACE_CLICK_NAME);
            logger.info("发送变量系统kafka人脸识别查询结果,data={}",JSONObject.toJSONString(kafkaData));
            producer.sendAsyncMessage(TracerContextUtil.getTraceId(), topicProperties.getProfileTopic(), JSONObject.toJSONString(kafkaData));
        }else{
            logger.warn("人脸识别异步查询结果result子集为空,无需推送变量系统,RES:{}",JSONObject.toJSONString(res));
        }


    }

    @ApiMapping(value = "tencent.queryApiVertifyFace2", desc = "腾讯.API人脸识别(formdata)",useCache = false)
    public Response queryApiVertifyFace(ApiVertifyFaceEntity entity, MultipartFile file){
        try {
            // 装载文件
            entity.setFile(file.getBytes());
        } catch (Exception e){
            logger.warn("tencent.queryApiVertifyFace setFile error，{}",e.getMessage());
            return new Response().fail(SystemErrorCodeEnum.JSS_PARAM_CHECK_FAILED.getResponseCode(),"未上传文件");
        }
        return queryApiVertifyFace(entity);
    }

    /***
     *  腾讯API 人脸识别
     * @param entity
     * @return
     */
    @ApiMapping(value = "tencent.queryApiVertifyFace", desc = "腾讯.API人脸识别",useCache = false)
    public Response queryApiVertifyFace(ApiVertifyFaceEntity entity){
        // 参数校验
        Response validResponse;
        validResponse = ValidUtil.valid(entity,First.class);
        if (entity.getFile().length>= FileUtils.ONE_MB * 3) {
            if (validResponse==null) {
                validResponse = new Response();
            }
            validResponse.fail(SystemErrorCodeEnum.JSS_PARAM_CHECK_FAILED.getResponseCode(),"文件过大");
        }
        if (validResponse!=null&&validResponse.checkIfFail()) {
            return validResponse;
        }
        Response response = new Response();
        //访问获取token
        String accessToken = faceRecognizeUtil.getAccessToken(response);
        if(StringUtils.isEmpty(accessToken)){
            return response;
        }
        //sign ticket 不需要userId
        String signTicket = faceRecognizeUtil.getTicket(accessToken,TencentConstant.FACE_TICKET_SIGN,null,response);
        if(StringUtils.isEmpty(signTicket)){
            return response;
        }
        // 签名加密
        String nonce= ServiceContext.genUniqueId();
        String [] signParams = new String[]{tencentProperties.getFaceAppId(),entity.getOrderNo(),nonce,TencentConstant.VERSION};
        List<String> signParamsList = new ArrayList<>();
        signParamsList.addAll(Arrays.asList(signParams));
        String sign = FaceRecognizeUtil.sign(signParamsList, signTicket);
        Map<String,String> params = new HashedMap();

        params.put("webankAppId",tencentProperties.getFaceAppId());
        params.put("nonce",nonce);
        params.put("version",TencentConstant.VERSION);
        params.put("sign",sign);
        params.put("orderNo",entity.getOrderNo());
        params.put("idNo",entity.getIdCard());
        params.put("name",entity.getName());
        params.put("userId",entity.getUserId());
        params.put("photoStr", Base64.encode(entity.getFile()));

        try {
            String resp = HttpClientUtils.httpPost(tencentProperties.getApiEasyface(),JSON.toJSONString(params));
            logger.info("腾讯API人脸识别接口，身份证号码：{}，请求返回值：{}",entity.getIdCard(),resp);
            // 上传文件
            uploadFileToOss(TencentConstant.API_VERTIFY_FACE, MD5Util.MD5(new String(entity.getFile())),
                    "img",entity.getFile());

            JSONObject data = JSON.parseObject(resp);
            // 校验成功失败
            if (data!=null && "0".equals(data.getString("code"))) {
                return response.success(data);
            }else {
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,data.getString("msg"),data);
            }
        } catch (Exception e){
            logger.warn("腾讯API人脸识别接口，身份证号码：{}，请求失败：{}",entity.getIdCard(),e.getMessage());
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR.getResponseCode(),e.getMessage());
        }
    }



    /**
     ********************************************************************
     * 上传文件至阿里云OSS
     * @param methodName 接口方法名
     * @param reqNo 请求流水号(此处为md5加密的byte流串)
     * @param fileType 文件类型
     * @param file byte文件流
     * @Author  zhangjialian
     * @return  void
     * @date    2018/9/3 17:33
     ********************************************************************/
    private void uploadFileToOss(String methodName, String reqNo ,String fileType,byte[] file) {
        try {
            String fileName=OssClientUtil.getKey(methodName,reqNo,fileType,null);
            List<OSSObjectSummary> ossObjectSummary= ossClientUtil.listObjects(fileName,1);
            if(ossObjectSummary!=null && ossObjectSummary.size()>0){
                logger.info("文件已存在，无需上传阿里云OSS:method={},reqNo={},fileType={},fileName={}",methodName,reqNo,fileType,fileName);
                return ;
            }
            logger.info("上传文件至阿里云OSS:method={},reqNo={},fileType={},fileName={}",methodName,reqNo,fileType,fileName);
            ossClientUtil.uploadFile(fileName,file);
        } catch (Throwable t) {
            logger.error("上传文件至阿里云OSS出现异常，异常信息:{}",t.getCause());
        }
    }

    /**
     ********************************************************************
     * 消息组装，通过kafka推送变量系统,做后续统计
     * @param jsonResult 推送结果内容
     * @param params 请求参数
     * @param methodName 接口类型名称
     * @Author  zhangjialian
     * @return  void
     * @date    2018/8/31 10:32
     ********************************************************************/
    private void sendAsyncMessage(JSONObject jsonResult, JSONObject params,String methodName) {
        CreditQueryRequest creditQueryRequest=new CreditQueryRequest();
        creditQueryRequest.setMethod(methodName);
        creditQueryRequest.setMobile(jsonResult.getString("phoneNo"));
        creditQueryRequest.setParams(params);
        String sendMsg=KafkaUtils.assembleKafkaMsg(creditQueryRequest,new Response().success(jsonResult));
        logger.info("发送变量系统kafka数据,data={}",sendMsg);
        producer.sendAsyncMessage(TracerContextUtil.getTraceId(), topicProperties.getProfileTopic(), sendMsg);
    }

    /**
     ********************************************************************
     * OCR识别结果解析
     * @param result ocr返回结果串
     * @Author  zhangjialian
     * @return  cn.touna.risk.api.domain.Response<java.lang.String>
     * @date    2018/8/10 14:50
     ********************************************************************/
    private Response parseOcrResult(String result) {
        Response response=new Response();
        JSONObject jsonObj=JSONObject.parseObject(result);
        if(StringUtils.isEmpty(result) || null==jsonObj){
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(),TencentConstant.OCR_RESULT_NULL);
        }
        String resultCode=jsonObj.get("code").toString();
        if(TencentConstant.OCR_SUCCESS_CODE.equals(resultCode)){//返回结果成功
            response.success(jsonObj.get("data"));
        }else{
            return response.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR.getErrorCode(),resultCode+"->"+jsonObj.get("message"));
        }
        return response;
    }

    /**
     ********************************************************************
     * 组装ocr 车辆识别header请求头
     * @param request 行驶证驾驶证识别请求对象
     * @Author  zhangjialian
     * @return  java.utils.Map<java.lang.String,java.lang.String>
     * @date    2018/8/10 14:20
     ********************************************************************/
    private HttpHeaders getOcrHeader(OcrRequest request) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.add("host",tencentProperties.getOcrHost());
        if (null!=request.getImage()){
            headers.add("content-type","multipart/form-data");
        } else if (request.getImage()==null && StringUtils.isNotEmpty(request.getUrl())){
            headers.add("content-type","application/json");
        }
        //生成签名所需信息必须使用主账号的，包括 APPID、Secret ID 和 Secret Key
        String sign= TencentOcrUtil.appSign(tencentProperties.getOcrAppid(),tencentProperties.getOcrSecretId(),
                tencentProperties.getOcrSecretKey(),null,60);
        headers.add("authorization",sign);
        return headers;
    }

    /**
     ********************************************************************
     * 检查行驶证驾驶证识别入参
     * @param request 行驶证驾驶证识别请求对象
     * @Author  zhangjialian
     * @return  cn.touna.risk.api.domain.Response<java.lang.String>
     * @date    2018/8/10 14:37
     ********************************************************************/
    private Response checkOcrRequest(OcrRequest request) {
        String msg=null;
        if (StringUtils.isEmpty(request.getType())){
            msg= TencentConstant.TYPE_IS_NULL;
        }else if(null==request.getImage() && StringUtils.isEmpty(request.getUrl())){
            msg= TencentConstant.IMAGE_OR_URL_IS_NULL;
        }
        if(StringUtils.isNotEmpty(msg)){
            return  new Response().fail(SystemErrorCodeEnum.JSS_PARAM_CHECK_FAILED.getErrorCode(),msg);
        }
        return null;

    }

   /**
    ********************************************************************
    * 组装ocr 识别header请求头
    * @param image
    * @param url
    * @Author  zhangjialian
    * @return  org.springframework.http.HttpHeaders
    * @date    2018/9/20 15:39
    ********************************************************************/
    private HttpHeaders getOcrHeader(byte[] image,String url) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.add("host",tencentProperties.getOcrHost());
        if (null!=image){
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        } else if (image==null && StringUtils.isNotEmpty(url)){
            headers.setContentType(MediaType.APPLICATION_JSON);
        }
        //生成签名所需信息必须使用主账号的，包括 APPID、Secret ID 和 Secret Key
        String sign= TencentOcrUtil.appSign(tencentProperties.getOcrAppid(),tencentProperties.getOcrSecretId(),
                tencentProperties.getOcrSecretKey(),null,60);
        headers.add("authorization",sign);
        return headers;
    }

    /**
     ********************************************************************
     * 检查身份证识别入参
     * @param request 行驶证驾驶证识别请求对象
     * @Author  zhangjialian
     * @return  cn.touna.risk.api.domain.Response<java.lang.String>
     * @date    2018/8/10 14:37
     ********************************************************************/
    private Response checkIdcardRequest(IdcardRequest request,byte[] image) {
        String msg=null;
        String cardType=request.getType();
        if(!"0".equals(cardType) && !"1" .equals(cardType)){
            msg= TencentConstant.CARDTYPE_NOT_VALID;
        }else if(null==image && StringUtils.isEmpty(request.getUrl())){
            msg= TencentConstant.IMAGE_OR_URL_IS_NULL;
        }else if(StringUtils.isEmpty(request.getMobile())){
            msg= TencentConstant.PARAMS_MOBILE_NULL;
        }else if(StringUtils.isEmpty(request.getImageMd5())){
            msg= TencentConstant.PARAMS_IMAGEMD5_NULL;
        }
        if(StringUtils.isNotEmpty(msg)){
            return  new Response().fail(SystemErrorCodeEnum.JSS_PARAM_CHECK_FAILED.getErrorCode(),msg);
        }
        return null;

    }
}
